package com.comm;

import com.dao.IMylog;
import com.model.MyLog;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.LocalVariableTableParameterNameDiscoverer;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Order(3)
@Component
@Aspect
public class LogAopAspect {
    @Autowired
    private IMylog iMylog;

    @Around(value = "@annotation(com.comm.MylogAnno)")
    public Object auoundAd(ProceedingJoinPoint pjp) {
        System.out.println("进入环形通知方法");
        //获取方法签名
        MethodSignature methodSignature = (MethodSignature) pjp.getSignature();

        //获取方法
        Method method = methodSignature.getMethod();

        //获取方法上面的注解
        MylogAnno mylogAnno = method.getAnnotation(MylogAnno.class);
        String oper = mylogAnno.OperateType();
        //获取访问接口时的各种操作
        MyLog myLog = new MyLog();
        MyLog.setUserID(" ");
        MyLog.setIPAdreess(HttpContextUtil.getIPAddress());

        //请求方法当中的类
        String className = pjp.getTarget().getClass().getName();
        String methodName = methodSignature.getName();
        MyLog.setDotime(className + "." + methodName);

        //请求方法的相关参数
        Object[] args = pjp.getArgs();
        System.out.println("获取参数的长度：" + args.length);
        LocalVariableTableParameterNameDiscoverer u = new LocalVariableTableParameterNameDiscoverer();
        String[] paramNames = u.getParameterNames(method);
        System.out.println("方法当中所涵盖的参数名称：" + paramNames.length);
        if (args != null && paramNames != null) {
            for (int i = 0; i < args.length; i++) {
                System.out.println(paramNames[i]);
                System.out.println(args[i]);
            }
        }


        Object result = null;
        try {
            long begin = System.currentTimeMillis();
            try {
                result = pjp.proceed();
            } catch (Throwable e) {
                e.printStackTrace();
            }

            long end = System.currentTimeMillis();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            iMylog.insertMyLog(myLog);
            System.out.println("将访问的接口信息记录到数据库中");
        }
        System.out.println("结束环形通知方法");
        return result;
    }
}
